//
//  GCObjectsLayer.m
//  GalaxyConqueror
//
//  Created by Test on 8/3/14.
//  Copyright (c) 2014 Stefan.Nestorov. All rights reserved.
//

#import "GCObjectsLayer.h"
#import "GCPlayerShip.h"
#import "GCEnemyShip.h"
#import "GCProjectile.h"

@implementation GCObjectsLayer
{
    
    NSMutableArray *_activeObjects;
    NSMutableArray *_projectiles;
    
}

-(instancetype)init
{
    
    self = [super init];
    if ( self ) {
        
        _playerShip = [[GCPlayerShip alloc] init];
        _playerShip.delegate = self;
        
        _activeObjects = [NSMutableArray new];
        _projectiles = [NSMutableArray new];
        
        [self addChild:_playerShip];
        
        [self addEnemyShip];
        
    }
    
    return self;
    
}


-(void)update:(CFTimeInterval)dt
{
    
    for (GCProjectile *projectile in _projectiles) {
        [projectile update:dt];
    }
    [self removeProjectilesIfNeeded];
    
    for (GCEnemyShip *enemyShip in _activeObjects) {
        [enemyShip update:dt];
    }
    [self removeEnemyShipsIfNeeded];
    
}


-(void)removeProjectilesIfNeeded
{
    
    NSMutableArray *projectilesToRemove = [NSMutableArray array];
    for (GCProjectile *projectile in _projectiles) {
        if ( projectile.shouldBeRemoved == YES ) {
            [projectilesToRemove addObject:projectile];
        }
    }
    
    if ( [projectilesToRemove count] > 0 ) {
        
        for (GCProjectile *projectile in projectilesToRemove) {
            [projectile removeFromParent];
        }
        
        [_projectiles removeObjectsInArray:projectilesToRemove];
    }
    
}

-(void)removeEnemyShipsIfNeeded
{

    NSMutableArray *enemyShipsToRemove = [NSMutableArray array];
    for (GCEnemyShip *enemyShip in _activeObjects) {
        if ( enemyShip.shouldBeRemoved == YES ) {
            [enemyShipsToRemove addObject:enemyShip];
        }
    }
    
    if ( [enemyShipsToRemove count] > 0 ) {
        
        for (GCEnemyShip *enemyShip in enemyShipsToRemove) {
            [enemyShip removeAllActions];
            [enemyShip removeFromParent];
        }
        
        [_activeObjects removeObjectsInArray:enemyShipsToRemove];
    }
    
}

-(void)addEnemyShip
{
    
    GCEnemyShip *enemyShip = [[GCEnemyShip alloc]init];
    enemyShip.delegate = self;
    [_activeObjects addObject:enemyShip];
    [self addChild:enemyShip];

}


-(void)addProjectile:(GCProjectile *)projectile
{
    
    [_projectiles addObject:projectile];
    [self addChild:projectile];
    
}


@end
